package biz.datalk.industrialland.common.component;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author tarofang@163.com
 * @date 2024-01-26
 */
public class SemaphoreReleaseOnlyOne {
    private final Semaphore semaphore;
    private final AtomicBoolean release = new AtomicBoolean(false);

    public SemaphoreReleaseOnlyOne(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException {
        return this.semaphore.tryAcquire(timeout, unit);
    }

    public void release() {
        if (release.compareAndSet(false, true)) {
            semaphore.release();
        }
    }
}
